Page({
  data: {
    image: '',
    type: '寻找爱宠',
    category: '',
    gender: '',
    name: '',
    address: '',
    city: '',
    date: '',
    description: '',
    cities: ['北京', '上海', '广州', '深圳']
  },
  goBack() {
    wx.navigateBack();
  },
  chooseImage() {
    const that = this;
    wx.chooseImage({
      count: 1,
      success(res) {
        that.setData({ image: res.tempFilePaths[0] });
      }
    });
  },

  onTypeChange(e) {
    this.setData({ type: e.detail.value });
  },

  onCategoryChange(e) {
    this.setData({ category: e.detail.value });
  },

  onGenderChange(e) {
    this.setData({ gender: e.detail.value });
  },

  onNameInput(e) {
    this.setData({ name: e.detail.value });
  },

  onAddressInput(e) {
    this.setData({ address: e.detail.value });
  },

  onCityChange(e) {
    this.setData({ city: this.data.cities[e.detail.value] });
  },

  onDateChange(e) {
    this.setData({ date: e.detail.value });
  },

  onDescriptionInput(e) {
    this.setData({ description: e.detail.value });
  },

  onSubmit() {
    const {
      type,
      name,
      description,
      city,
      address,
      image,
      gender,
      date
    } = this.data;
    console.log('提交值:', { name, address, gender });

    if (!name || !address || !gender) {
      wx.showToast({ title: '请填写完整信息', icon: 'none' });
      return;
    }
  
    wx.showLoading({ title: '发布中...' });
  
    wx.request({
      url: 'http://localhost:3000/posts/create', // 替换为你服务器实际地址
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        post_type: type,
        name,
        description,
        city,
        image_urls: [image], // 此处为数组，后台 JSON 类型字段
        status: 1
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.code === 200) {
          wx.showToast({ title: '发布成功', icon: 'success' });
          wx.navigateBack(); // 或跳转到列表页
        } else {
          wx.showToast({ title: res.data.message || '发布失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({ title: '请求失败', icon: 'none' });
      }
    });
  }
  
  
});
